package com.iap.admin.mediator
{
	import com.iap.admin.event.TagEvent;
	import com.iap.common.signal.TagRequestSignal;
	import com.iap.admin.view.AdminMenuView;
	import com.iap.admin.view.TagView;
	import com.iap.admin.view.tag.TagEditView;
	import com.iap.app.AppGlobal;
	import com.iap.common.model.Tag;
	
	import mx.collections.ArrayList;
	
	import spark.components.Group;
	import spark.events.GridEvent;
	import com.iap.common.mediator.BaseMediator;

	public class TagMediator extends BaseMediator
	{
		[Inject]
		public var view:TagView;
		[Inject]
		public var request:TagRequestSignal;

		override public function onRegister():void
		{
			view.onOptionClick.add(onClick);
			addContextListener(TagEvent.RESPONSE, responseHandler);
			addViewListener(GridEvent.GRID_CLICK, gridClickEvent);
			dispatchRequest();
		}
		
		private function gridClickEvent(evt:GridEvent):void
		{ 
			var item:Tag = evt.item as Tag;
			if(item==null) return;
			edit(item);
		}
		
		private function dispatchRequest():void
		{
			AppGlobal.startWait();
			request.dispatch(new Tag(), TagRequestSignal.GET);
		}
		
		private function responseHandler(evt:TagEvent):void
		{
			AppGlobal.endWait();
			view.datagrid.dataProvider = new ArrayList(evt.response.result as Array);
		}
		
		private function onClick(itemName:String):void
		{
			switch(itemName)
			{
				case TagView.HOME_NAME:
				{
					home();
					break;
				}
				case TagView.CREATE_NAME:
				{
					create();
					break;
				}
				default:
				{
					break;
				}
			}
		}
		
		private function home():void
		{
			setView(view.parent as Group, new AdminMenuView(), FX_GLIDE_OUT);
		}
		
		
		private function create():void
		{
			setView(view.parent as Group, new TagEditView());
		}
		
		private function edit(item:Tag):void
		{
			var newView:TagEditView = new TagEditView();
			newView.onReady.addOnce(function(str:String):void{
				newView.fill(item);
			});
			setView(view.parent as Group, newView);
		}
	}
}